<?php
// 订单详情
function order($json , $session)
{
	$ret = array() ;
	$ret['data'] = array() ;
	$ret['data']['order'] = array() ;
	
	$uid = util_set_GETUID_for_SESSION($session) ;
	if ($uid <= 0)
	{
		$ret['status'] = $GLOBALS["ERR"]["ERR_USER_NOTFIND"] ;
		$ret['message'] = $GLOBALS["MES"]["ERR_USER_NOTFIND"] ;
		return $ret ;
	}
	
	$out_trade_no = get_jsonValue($json,"id") ;		// 我们自己的订单编号
	$one_trade = sql_fetch_one("select * from pay_trade where `trade_no` = '$out_trade_no'") ;
	
	// 订单不存在
	if (is_null($one_trade) == true || array_key_exists('user_id', $one_trade) == false || $one_trade['user_id'] != $uid){
		$ret['status'] = $GLOBALS["ERR"]["ERR_TRADE_INVITE"] ;
		$ret['message'] = $GLOBALS["MES"]["ERR_TRADE_INVITE"] ;
		return $ret ;
	}
	
	$ret['data']['order'] = array() ;
	util_set_ORDER($ret['data']['order'] , $one_trade) ;
		
	return $ret ;
}
// 订单详情
function order_list($json , $session)
{
	$ret = array() ;
	$ret['data'] = array() ;
	$ret['data']['list'] = array() ;
	
	$uid = util_set_GETUID_for_SESSION($session) ;
	if ($uid <= 0)
	{
		$ret['status'] = $GLOBALS["ERR"]["ERR_USER_NOTFIND"] ;
		$ret['message'] = $GLOBALS["MES"]["ERR_USER_NOTFIND"] ;
		return $ret ;
	}
	
	$offset = 0 ;
	$limit = 0 ;
	util_get_PAGINATION($json , $offset , $limit) ;
	$status = get_jsonValue($json,"status") ;		// 状态
	
	$addwhere = "" ;
	if (strlen($status) > 0){
		$status = intval($status) ;
		
		if ($status == 0 || $status == 8){
			$addwhere .= " and (`trade_state` = '0' or (`trade_state` = '1' and `price_state` = '11')) " ;
		}else{
			
			if ($status == 1){
				$addwhere .= " and `trade_state` = '1' and `price_state` != '11'" ;
			}else{
				$addwhere .= " and `trade_state` = '$status'" ;
			}
		}
	}
	
	// 组织页面数据
	$start = ($offset - 1) * $limit ;	
	$allcount = sql_fetch_one_cell("select count(user_id) from pay_trade where `user_id` = '$uid' $addwhere") ;
	
	$ret['data']['pagination'] = array() ;
	util_set_PAGINATION($ret['data']['pagination'] , $allcount , $limit , $offset) ;
	
	$tradelist = sql_fetch_rows("select * from pay_trade where `user_id` = '$uid' $addwhere order by `create_time` desc limit $start , $limit") ;
	
	foreach ($tradelist as $t)
	{
		$one = array() ;
		util_set_ORDER_SIMPLE($one , $t) ;
		$ret['data']['list'][] = $one ;
	}
	
	return $ret ;
}
// 关闭订单
function order_close($json , $session)
{
	$ret = array() ;
	$ret['data'] = array() ;
	
	$uid = util_set_GETUID_for_SESSION($session) ;
	if ($uid <= 0)
	{
		$ret['status'] = $GLOBALS["ERR"]["ERR_USER_NOTFIND"] ;
		$ret['message'] = $GLOBALS["MES"]["ERR_USER_NOTFIND"] ;
		return $ret ;
	}
	
	$out_trade_no = get_jsonValue($json,"id") ;		// 我们自己的订单编号
	$one_trade = sql_fetch_one("select * from pay_trade where `trade_no` = '$out_trade_no'") ;
	
	// 订单不存在
	if (is_null($one_trade) == true || array_key_exists('user_id', $one_trade) == false || $one_trade['user_id'] != $uid){
		$ret['status'] = $GLOBALS["ERR"]["ERR_TRADE_INVITE"] ;
		$ret['message'] = $GLOBALS["MES"]["ERR_TRADE_INVITE"] ;
		return $ret ;
	}
	//  只有在订单状态  0 - 待处理(未付款),6 待询价 时候可以 关闭订单(2 订单取消(交易关闭))
	if (intval($one_trade['trade_state']) != 0 && intval($one_trade['trade_state']) != 6)
	{
		$ret['status'] = $GLOBALS["ERR"]["ERR_TRADE_STATE"] ;
		$ret['message'] = $GLOBALS["MES"]["ERR_TRADE_STATE"] ;
		return $ret ;
	}
	
	$state = intval(get_jsonValue($json,"state")) ;	
	$memo = get_jsonValue($json,"cancel_reason") ;
	if (is_null($memo))	$memo = "" ;

	sql_query("update pay_trade set `trade_state` = 2 , `cancel_state` = '$state' , `cancel_memo` = '$memo' where `trade_no` = '$out_trade_no'") ;
	$one_trade = sql_fetch_one("select * from pay_trade where `trade_no` = '$out_trade_no'") ;
	
	$ret['data']['order'] = array() ;
	util_set_ORDER($ret['data']['order'] , $one_trade) ;
		
	return $ret ;
}
// 删除订单
function order_delete($json , $session)
{
	$ret = array() ;
	$ret['data'] = array() ;
	
	$uid = util_set_GETUID_for_SESSION($session) ;
	if ($uid <= 0)
	{
		$ret['status'] = $GLOBALS["ERR"]["ERR_USER_NOTFIND"] ;
		$ret['message'] = $GLOBALS["MES"]["ERR_USER_NOTFIND"] ;
		return $ret ;
	}
	
	$out_trade_no = get_jsonValue($json,"id") ;		// 我们自己的订单编号
	$one_trade = sql_fetch_one("select * from pay_trade where `trade_no` = '$out_trade_no'") ;
	
	// 订单不存在
	if (is_null($one_trade) == true || array_key_exists('user_id', $one_trade) == false || $one_trade['user_id'] != $uid){
		$ret['status'] = $GLOBALS["ERR"]["ERR_TRADE_INVITE"] ;
		$ret['message'] = $GLOBALS["MES"]["ERR_TRADE_INVITE"] ;
		return $ret ;
	}
	//  只有在订单状态  2 - 只有取消了的订单可以被删除
	if (intval($one_trade['trade_state']) != 2)
	{
		$ret['status'] = $GLOBALS["ERR"]["ERR_TRADE_STATE"] ;
		$ret['message'] = $GLOBALS["MES"]["ERR_TRADE_STATE"] ;
		return $ret ;
	}
	
	$id = $one_trade['id'] ;
	
	sql_query("insert into pay_trade_del select * from pay_trade where `id` = '$id'") ;
	sql_query("delete from pay_trade where `id` = '$id'") ;

	$ret['data']['order'] = array() ;
	util_set_ORDER($ret['data']['order'] , $one_trade) ;		
	return $ret ;	
}
// 确认收货（交易完成）
function order_recive($json , $session)
{
	$ret = array() ;
	$ret['data'] = array() ;
	
	$uid = util_set_GETUID_for_SESSION($session) ;
	if ($uid <= 0)
	{
		$ret['status'] = $GLOBALS["ERR"]["ERR_USER_NOTFIND"] ;
		$ret['message'] = $GLOBALS["MES"]["ERR_USER_NOTFIND"] ;
		return $ret ;
	}
	
	$out_trade_no = get_jsonValue($json,"id") ;		// 我们自己的订单编号
	$one_trade = sql_fetch_one("select * from pay_trade where `trade_no` = '$out_trade_no'") ;
	
	// 订单不存在
	if (is_null($one_trade) == true || array_key_exists('user_id', $one_trade) == false || $one_trade['user_id'] != $uid){
		$ret['status'] = $GLOBALS["ERR"]["ERR_TRADE_INVITE"] ;
		$ret['message'] = $GLOBALS["MES"]["ERR_TRADE_INVITE"] ;
		return $ret ;
	}
	//  只有在订单状态  7 - 已发货(待收货) 时候可以 确认收货
	if (intval($one_trade['trade_state']) != 7)
	{
		$ret['status'] = $GLOBALS["ERR"]["ERR_TRADE_STATE"] ;
		$ret['message'] = $GLOBALS["MES"]["ERR_TRADE_STATE"] ;
		return $ret ;
	}

	$no_id = intval($one_trade['id']) ;
	sql_query("update pay_logistics set `logistics_state` = 2 where `trade_id` = '$no_id'") ;
	sql_query("update pay_trade set `trade_state` = 3 , `over_time` = unix_timestamp() where `id` = '$no_id'") ;
	
	$one_trade = sql_fetch_one("select * from pay_trade where  `id` = '$no_id'") ;
	
	$ret['data']['order'] = array() ;
	util_set_ORDER($ret['data']['order'] , $one_trade) ;
		
	return $ret ;
}
// 物流查询
function order_logistics_query($json , $session)
{
	$ret = array() ;
	$ret['data'] = array() ;
	
	$uid = util_set_GETUID_for_SESSION($session) ;
	if ($uid <= 0)
	{
		$ret['status'] = $GLOBALS["ERR"]["ERR_USER_NOTFIND"] ;
		$ret['message'] = $GLOBALS["MES"]["ERR_USER_NOTFIND"] ;
		return $ret ;
	}
	
	$out_trade_no = get_jsonValue($json,"order_id") ;			// 我们自己的订单编号
	$waybill_number = get_jsonValue($json,"waybill_number") ;	// 运单编号
	$one_trade = sql_fetch_one("select * from pay_trade where `trade_no` = '$out_trade_no'") ;
	
	// 订单不存在
	if (is_null($one_trade) == true || array_key_exists('user_id', $one_trade) == false || $one_trade['user_id'] != $uid){
		$ret['status'] = $GLOBALS["ERR"]["ERR_TRADE_INVITE"] ;
		$ret['message'] = $GLOBALS["MES"]["ERR_TRADE_INVITE"] ;
		return $ret ;
	}
	//  只有在订单状态  7 - 已发货(待收货) 时候可以 查询物流信息
	if (intval($one_trade['trade_state']) != 7)
	{
		$ret['status'] = $GLOBALS["ERR"]["ERR_TRADE_STATE"] ;
		$ret['message'] = $GLOBALS["MES"]["ERR_TRADE_STATE"] ;
		return $ret ;
	}	
	$logistics_name = sql_fetch_one_cell("select logistics_name from pay_logistics where `logistics_trade` = '$waybill_number' ") ;
	
	$kd = sql_fetch_one("select * from grp_kuaidi where `code` = '$logistics_name'") ;
	if (is_array($kd) == false){
		$ret['status'] = -997 ;
		$ret['message'] = "快递公司编码错误:" . $logistics_name ;
		return $ret ;		
	}
	$code_kuaidi = $kd['code'] ;
	if ($code_kuaidi != $logistics_name || strlen($logistics_name) == 0)
	{
		$ret['status'] = -997 ;
		$ret['message'] = "快递公司编码错误:" . $logistics_name ;
		return $ret ;
	}
	
	$data = null ;
	
	try{
		//参数设置
		$post_data = array();
		$post_data["customer"] = 'DB18967F63113F1BF97A0AC6773E31C5';
		$key= 'YjPgYUqw7427' ;
		$post_data["param"] = '{"com":"' . $logistics_name . '","num":"' . $waybill_number . '"}';
	
		$url='http://poll.kuaidi100.com/poll/query.do';
		$post_data["sign"] = md5($post_data["param"].$key.$post_data["customer"]);
		$post_data["sign"] = strtoupper($post_data["sign"]);
		
		$data = json_decode(request_post($url , $post_data) , true) ;
		
	}catch(Exception $e){
		$ret['status'] = -999 ;
		$ret['message'] = $e->getMessage() ;
		return $ret ;
	}
	if (is_null($data)){
		$ret['status'] = -998 ;
		$ret['message'] = "获取失败" ;
		return $ret ;
	}	
	if (array_key_exists('returnCode' , $data) == true && array_key_exists('state' , $data) == false)
	{
		$ret['status'] = $data['returnCode'] ;
		$ret['message'] = $data['message'] ;
		return $ret ;
	}
	
	
	$ret['logistics_status'] = array() ;
	util_set_LOGISTICS_STATUS($ret['logistics_status'] , $data , $kd['name']) ;
	return $ret ;
}
// 运单号查询
function order_Waybill_query($json , $session)
{
	$ret = array() ;
	$ret['data'] = array() ;
	
	$uid = util_set_GETUID_for_SESSION($session) ;
	if ($uid <= 0)
	{
		$ret['status'] = $GLOBALS["ERR"]["ERR_USER_NOTFIND"] ;
		$ret['message'] = $GLOBALS["MES"]["ERR_USER_NOTFIND"] ;
		return $ret ;
	}
	
	$out_trade_no = get_jsonValue($json,"order_id") ;			// 我们自己的订单编号
	$one_trade = sql_fetch_one("select * from pay_trade where `trade_no` = '$out_trade_no'") ;
	
	// 订单不存在
	if (is_null($one_trade) == true || array_key_exists('user_id', $one_trade) == false || $one_trade['user_id'] != $uid){
		$ret['status'] = $GLOBALS["ERR"]["ERR_TRADE_INVITE"] ;
		$ret['message'] = $GLOBALS["MES"]["ERR_TRADE_INVITE"] ;
		return $ret ;
	}	
	//  只有在订单状态  7 - 已发货(待收货) 时候可以 查询物流信息
	if (intval($one_trade['trade_state']) != 7)
	{
		$ret['status'] = $GLOBALS["ERR"]["ERR_TRADE_STATE"] ;
		$ret['message'] = $GLOBALS["MES"]["ERR_TRADE_STATE"] ;
		return $ret ;
	}
	
	// 返回 `WAYBILL_NUMBER`数组 | 物流单信息
	$ret['data']['Waybill'] = array() ;
	$no_id = $one_trade['id'] ; 
	$logistics = sql_fetch_rows("select * from pay_logistics where `trade_id` = '$no_id'") ;
	
	$arr_tics = array() ;
	foreach($logistics as $ls){
		$logistics_trade = $ls['logistics_trade'] ;
		if (array_key_exists($logistics_trade, $arr_tics) == false){
			$arr_tics[$logistics_trade] = array() ;
		}
		$arr_tics[$logistics_trade][] = $ls ;
	}
	
	foreach($arr_tics as $ts){
		$a = array() ;
		util_set_WAYBILL_NUMBER($a , $ts) ;
		$ret['data']['Waybill'][] = $a ;
	}
	return $ret ;
}

// 订单支付详情查询
function pay_order_query($json , $session)
{
	$ret = array() ;
	$ret['data'] = array() ;
	
	$uid = util_set_GETUID_for_SESSION($session) ;
	if ($uid <= 0)
	{
		$ret['status'] = $GLOBALS["ERR"]["ERR_USER_NOTFIND"] ;
		$ret['message'] = $GLOBALS["MES"]["ERR_USER_NOTFIND"] ;
		return $ret ;
	}
	
	$out_trade_no = get_jsonValue($json,"order_id") ;		// 我们自己的订单编号
	$one_trade = sql_fetch_one("select * from pay_trade where `trade_no` = '$out_trade_no'") ;
	
	// 订单不存在
	if (is_null($one_trade) == true || array_key_exists('user_id', $one_trade) == false || $one_trade['user_id'] != $uid){
		$ret['status'] = $GLOBALS["ERR"]["ERR_TRADE_INVITE"] ;
		$ret['message'] = $GLOBALS["MES"]["ERR_TRADE_INVITE"] ;
		return $ret ;
	}
	
	$ret['data']['pay_detail'] = array() ;
	$log_pay = sql_fetch_rows("select * from log_pay where `trade_no` = '$out_trade_no' and `state` = '2' order by `trade_no_count` asc ") ;
	if (!is_array($log_pay)){
		return $ret ;
	}
	
	
	$idx = 1 ;
	foreach($log_pay as $lg)
	{
		$a = array() ;
		$a['index'] = $idx ;					$idx ++ ;
		$a['pay_amount'] = $lg['rmb'] ;		
		
		$ret['data']['pay_detail'][] = $a ;
	}
	
	return $ret ;
}

// 根据订单号生成物流表信息
function create_logistics_for_trade($trade_id)
{
	$tradeinfo = sql_fetch_one("select * from pay_trade where `trade_no` = '$trade_id'") ;
	if (is_array($tradeinfo) == false)		return false ;
	
	$id = intval($tradeinfo['id']) ;
	if ($id <= 0)		return false ;
	
	sql_query("delete from `pay_logistics` where `trade_id` = '$id'") ;
	
	
	$address = "" ;
	$mobile = "" ;
	$addlist = explode(";" , $tradeinfo['address']) ;
	if (count($addlist) >= 1)	$address .= $addlist[0] ;			// 详细地址
	if (count($addlist) >= 2)	$address .= "(".$addlist[1].")" ;	// 收货人姓名
	if (count($addlist) >= 3)	$mobile  = $addlist[2] ;			// 手机号
	
	$itemlist = array() ;
	util_set_ORDER_addlist($itemlist, $tradeinfo['content'] , true) ;	
	foreach($itemlist as $it){
		$item_id = $it["item_id"] ;
		$item_memo = $it["source_json"] ;
		$number = $it["number"] ;
		
		sql_insert("INSERT INTO `pay_logistics` (`trade_id`, `item_id`, `item_memo`, `number`, `accept_address`, `accept_photo`) VALUES ('$id', '$item_id', '$item_memo', '$number', '$address', '$mobile')") ;		
	}
	return true ;
}

// 检查订单里所有单品是否有下架状态的.
function check_all_trade_is_ok_pay($trade_id)
{
    $tradeinfo = sql_fetch_one("select * from pay_trade where `trade_no` = '$trade_id'") ;
    if (is_array($tradeinfo) == false)		return false ;

    $id = intval($tradeinfo['id']) ;
    if ($id <= 0)		return false ;

    if (intval($tradeinfo['price_state']) == 11 )       return true ;

    $itemlist = array() ;
    util_set_ORDER_addlist($itemlist, $tradeinfo['content'] , true) ;
    foreach($itemlist as $it) {
        $item_id = $it["item_id"];
        $isp = intval(sql_fetch_one_cell("select `app_return` from sys_item where `id` = '$item_id'")) ;
        if ($isp != 1){
            return false ;
        }
    }
    return true ;
}


//TODO 下边所有调用接口都是微信相关 , 上边公用接口.可能支付宝,银联都会用到
//---------------------------------------------------------------------


// 用户登录 - 微信登陆
function user_signin_weixin($json , $session)
{
	$access_token	= get_jsonValue($json,"access_token") ;	// token
	$openid	 		= get_jsonValue($json,"openid") ;		// openid
	
	$uid = util_set_GETUID_for_SESSION($session) ;
	if ($uid > 0){
		$one = sql_fetch_one("select * from user_login_other where `uid` = '$uid' and `type` = 1 and `out_time` > unix_timestamp()") ;
		if (is_array($one) == false || array_key_exists("uid" , $one) == false){
			$wx_res	= getWeiXinUserinfo($access_token , $openid) ; 
			$wx_arr = json_decode($wx_res) ;
			$unionid = get_jsonValue($wx_arr,"unionid") ;
			$nickname = get_jsonValue($wx_arr,"nickname") ;
			$deadline_day = 60 * 60 * 24 * 3 ;	// 3天后token过期.
			
			sql_insert("insert into user_login_other (`uid` , `type` , `out_time` , `param1` , `param2` , `param3`) values ('$uid' , '1' , unix_timestamp() + $deadline_day , '$unionid' , '$wx_res' , '$access_token')  ON DUPLICATE KEY UPDATE `out_time` = unix_timestamp() + $deadline_day , `param1` = '$unionid' , `param2` =  '$wx_res' , `param3` = '$access_token'") ;
			$one = sql_fetch_one("select * from user_login_other where `uid` = '$uid' and `type` = 1 and `out_time` > unix_timestamp()") ;
		}
		if (is_array($one) && array_key_exists("uid" , $one) == true){
			$jsondata = $one['param2'] ;
			$wx_arr = json_decode($jsondata) ;	
			$unionid = get_jsonValue($wx_arr,"unionid") ;
			$nickname = get_jsonValue($wx_arr,"nickname") ;
			$tokn = substr(md5($nickname . $unionid . time()) . $unionid , 2 , 38) ; 
			return _user_getinfo($uid , $tokn) ;
		}else{
			$ret = array() ;
			$ret['data'] = array() ;
			$ret['status'] = $GLOBALS["ERR"]["ERR_USER_NOTFIND"] ;
			$ret['message'] = $GLOBALS["MES"]["ERR_USER_NOTFIND"] ;
			return $ret ;			
		}
	}
	
	$one = sql_fetch_one("select * from user_login_other where `param3` = '$access_token' and `type` = 1 and `out_time` > unix_timestamp()") ;
	if (is_array($one) == false || array_key_exists("uid" , $one) == false){
		$wx_res	= getWeiXinUserinfo($access_token , $openid) ; 
		$wx_arr = json_decode($wx_res) ;
	}else{
		$wx_res = $one['param2'] ;
		$wx_arr = json_decode($wx_res) ;
	}
	// 有可能是新的微信用户
	$unionid = get_jsonValue($wx_arr,"unionid") ;
	$nickname = get_jsonValue($wx_arr,"nickname") ;
	$usersex = get_jsonValue($wx_arr,"sex") ;
	$deadline_day = 60 * 60 * 24 * 3 ;	// 3天后token过期.
	
	$invite_code = "" ;	// 邀请码
	
	$one = sql_fetch_one("select * from user_login_other where `param1` = '$unionid' and `type` = 1") ;
	if (is_array($one) == false || array_key_exists("uid" , $one) == false){
		// 注册一个新用户
		$uinfo = _user_regist_insert($unionid , $nickname , $invite_code , $unionid , $unionid , $unionid , 4 , $usersex==1?"男":"女") ;
		$tokn = $uinfo[0] ;
		$uid = $uinfo[1] ;
		
		sql_insert("insert into user_login_other (`uid` , `type` , `out_time` , `param1` , `param2` , `param3`) values ('$uid' , '1' , unix_timestamp() + $deadline_day , '$unionid' , '$wx_res' , '$access_token')  ON DUPLICATE KEY UPDATE `out_time` = unix_timestamp() + $deadline_day , `param1` = '$unionid' , `param2` =  '$wx_res' , `param3` = '$access_token'") ;
		$one = sql_fetch_one("select * from user_login_other where `uid` = '$uid' and `type` = 1 and `out_time` > unix_timestamp()") ;
	}else{
		$uid = $one['uid'] ;
		sql_query("update user_login_other set  `out_time` = unix_timestamp() + $deadline_day , `param3` = '$access_token' where `uid` = '$uid' ") ;
	}

	$tokn = substr(md5($nickname . $unionid . time()) . $unionid , 2 , 38) ; 
	return _user_getinfo($uid , $tokn) ;
}

// 微信充值获取预充值数据参数(微信统一下单)
function pay_weixin($json , $session)
{
	$ret = array() ;
	$ret['data'] = array() ;
	
	$uid = util_set_GETUID_for_SESSION($session) ;
	if ($uid <= 0)
	{
		$ret['status'] = $GLOBALS["ERR"]["ERR_USER_NOTFIND"] ;
		$ret['message'] = $GLOBALS["MES"]["ERR_USER_NOTFIND"] ;
		return $ret ;
	}
	
	$out_trade_no = get_jsonValue($json,"order_id") ;		// 我们自己的订单编号
	$one_trade = sql_fetch_one("select * from pay_trade where `trade_no` = '$out_trade_no' and `user_id` = '$uid'") ;
	
	// 订单不存在
	if (is_null($one_trade) == true || array_key_exists('user_id', $one_trade) == false){
		$ret['status'] = $GLOBALS["ERR"]["ERR_TRADE_INVITE"] ;
		$ret['message'] = $GLOBALS["MES"]["ERR_TRADE_INVITE"] ;
		return $ret ;
	}
	// 订单状态错误
	if (intval($one_trade['trade_state']) != 0 || intval($one_trade['price_state']) != 0)
	{
		$ret['status'] = $GLOBALS["ERR"]["ERR_PAY_STATE"] ;
		$ret['message'] = $GLOBALS["MES"]["ERR_PAY_STATE"] ;
		return $ret ;
	}
	// 价格不能小于0
	if (doubleval($one_trade['price']) < 0){
		$ret['status'] = $GLOBALS["ERR"]["ERR_PAY_ZERO"] ;
		$ret['message'] = $GLOBALS["MES"]["ERR_PAY_ZERO"] ;
		return $ret ;
	}
	// 价格不能为0
	if (doubleval($one_trade['price']) == 0  && doubleval($one_trade['price_modify']) == 0  ){
		$ret['status'] = $GLOBALS["ERR"]["ERR_PAY_ZERO"] ;
		$ret['message'] = $GLOBALS["MES"]["ERR_PAY_ZERO"] ;
		return $ret ;
	}

	// 订单价格更改后必须经过审核才允许用户付钱.
	if (doubleval($one_trade['price']) != doubleval($one_trade['price_modify'])){
		if (intval($one_trade['audit_state']) != 1){
			$ret['status'] = $GLOBALS["ERR"]["ERR_PAY_NOAUDIT"] ;
			$ret['message'] = $GLOBALS["MES"]["ERR_PAY_NOAUDIT"] ;
			return $ret ;
		}
	}
	
	// 支付金额和汇总付款金额检测
	$money = doubleval($one_trade['price_modify']) ;		// 实际需要支付金额
	if ($money > 5000)
	{
		// 可能需要分批支付,每笔5000.
	}
	$body = "JAJAHOME付款 $money 元" ;
	
	$result = getWeiXin_AppPay_unifiedorder($body , $out_trade_no , $money) ;	
	if ($result['return_code'] == "SUCCESS" && $result['result_code'] == "SUCCESS")
	{
		$prepay_id = $result['prepay_id'] ;	// 微信返回的支付交易会话ID		
		$memo_xml = $result['document_result'] ;		
		// 统一下单成功
		sql_query("delete from `log_pay` where `trade_no` = '$out_trade_no' and `trade_no_count` = 0 and `state` not in ( 1 , 2)") ;
		sql_query("insert into `log_pay` (`prepay_id` , `transaction_id`, `trade_no`, `uid`, `type`, `starttime`, `endtime`, `memo_xml`, `rmb`, `state`, `state_count`) VALUES ('$prepay_id' , '$prepay_id' , '$out_trade_no', '$uid', '1', unix_timestamp(), '0', '$memo_xml', '$money', '0', '0') ") ;
		$save_tr_id = sql_fetch_one_cell("select `prepay_id` from `log_pay` where `prepay_id` = '$prepay_id'") ;
		if ($prepay_id != $save_tr_id){
			$ret['status'] = $GLOBALS["ERR"]["ERR_DATABASE"] ;
			$ret['message'] = $GLOBALS["MES"]["ERR_DATABASE"] ;
			return $ret ;
		}
		
		$param = array() ;
		$param["appid"]				= $GLOBALS['WX_APPID'] ;	// 公众账号ID
		$param["partnerid"]			= $GLOBALS['WX_MCHID'] ;	// 商户号
		$param["prepayid"]			= $prepay_id ;			// 微信返回的支付交易会话ID
		$param["noncestr"]			= md5("G8a2fe938d2j" . time());		// 随机字符串 不长于32位
		$param["timestamp"]			= time() ;					// 时间戳
		$param["package"]			= "Sign=WXPay" ;			// 暂填写固定值Sign=WXPay			
		$param["sign"]				= strtoupper(md5(getParamAuto($param,false) . "&key={$GLOBALS['WX_KEY']}")) ;
		
		$ret['data']['pay_info'] = array() ;
		
		
		$ret['data']['pay_info']['partnerid'] 	= $param["partnerid"] ;		// 商户号
		$ret['data']['pay_info']['prepayid'] 	= $param["prepayid"] ;		// 微信返回的支付交易会话ID
		$ret['data']['pay_info']['noncestr'] 	= $param["noncestr"] ;		// 随机字符串 不长于32位
		$ret['data']['pay_info']['timestamp'] 	= $param["timestamp"] ;		// 时间戳
		$ret['data']['pay_info']['package'] 	= $param["package"] ;		// 暂填写固定值Sign=WXPay
		$ret['data']['pay_info']['sign'] 		= $param["sign"] ;			// 签名
		$ret['data']['pay_info']['appid'] 		= $param["appid"] ;
		
		$ret['data']['pay_info']['trade_no'] 	= $out_trade_no ;			// 商户订单号
	}
	else
	{
		$ret['data']['pay_info'] = array() ;
		$ret['data']['pay_info']['error_code'] = $result['err_code'] ;
		$ret['data']['pay_info']['error_desc'] = $result['err_code_des'] ;
		
		$ret['status'] = 88 ;	// 下单失败
		$ret['message'] = "调用统一下单失败:" ;
		if ($result['return_code'] == "FAIL"){
			$ret['message'] .= $result['return_msg'] ;
		} 
		if ($result['return_code'] == "FAIL"){
			$ret['message'] .= "(" . $result['err_code'] . ")" . $result['err_code_des'];
		}
	}
	return $ret ;
}


// 用户订单状态检测,查看此订单是否可以支付
function pay_trade_state_check($out_trade_no , $uid , $order_price , $pay_count)
{
	$ret = array() ;
	$ret['data'] = array() ;
	
	if (doubleval($order_price) <= 0){
		$ret['status'] = $GLOBALS["ERR"]["ERR_PAY_ZERO"] ;
		$ret['message'] = "支付的金额不能为0" ;
		return $ret ;
	}
	
	$one_trade = sql_fetch_one("select * from pay_trade where `trade_no` = '$out_trade_no'") ;
	// 订单不存在
	if (is_null($one_trade) == true || array_key_exists('user_id', $one_trade) == false){
		$ret['status'] = $GLOBALS["ERR"]["ERR_TRADE_INVITE"] ;
		$ret['message'] = $GLOBALS["MES"]["ERR_TRADE_INVITE"] ;
		return $ret ;
	}
	if (intval($one_trade['user_id']) != $uid || $uid == 0)
	{
		$ret['status'] = $GLOBALS["ERR"]["ERR_TRADE_INVITE"] ;
		$ret['message'] = "此订单不是您的订单" ;
		return $ret ;
	}
	// 订单状态错误
	switch(intval($one_trade['price_state'])){
		case 0 :	break ;		// 0 - 待付款 可以继续支付
		case 11 :	break ;		// 11 - 已付部分(未完全付款)'
		
		case 1 :	
			$ret['status'] = $GLOBALS["ERR"]["ERR_PAY_STATE"] ;
			$ret['message'] = "此订单您已经付款成功,不用再次付款" ;
			return $ret ;
		case 2 :	
			$ret['status'] = $GLOBALS["ERR"]["ERR_PAY_STATE"] ;
			$ret['message'] = "此订单为待退款状态,无法支付" ; 
			return $ret ;
		case 3 :	
			$ret['status'] = $GLOBALS["ERR"]["ERR_PAY_STATE"] ;
			$ret['message'] = "此订单您已经退款,订单失效" ;	
			return $ret ;
		default :	
			$ret['status'] = $GLOBALS["ERR"]["ERR_PAY_STATE"] ;
			$ret['message'] = $GLOBALS["MES"]["ERR_PAY_STATE"] ;
			return $ret ;
	}
		
	switch(intval($one_trade['trade_state'])){
		case 0 :		break ;		// 0 - 待处理 , 可以支付
		case 1 :		break ;		// 1 - 已付款 			-- 只要钱没付完,都可以继续支付
		case 7 :		break ;		// 7 - 已发货(待收货)	-- 只要钱没付完,都可以继续支付
		case 9 :	
			$ret['status'] = $GLOBALS["ERR"]["ERR_PAY_STATE"] ;
			$ret['message'] = "上次支付正在审核" ; 
			return $ret ;
		case 2 :
			$ret['status'] = $GLOBALS["ERR"]["ERR_PAY_STATE"] ;
			$ret['message'] = "此订单您已经取消,失效订单" ; 
			return $ret ;
		case 3 :
			$ret['status'] = $GLOBALS["ERR"]["ERR_PAY_STATE"] ;
			$ret['message'] = "此订单已经完成,无法支付" ; 
			return $ret ;
		case 4 :
			$ret['status'] = $GLOBALS["ERR"]["ERR_PAY_STATE"] ;
			$ret['message'] = "此订单正在退款中" ; 
			return $ret ;
		case 5 :
			$ret['status'] = $GLOBALS["ERR"]["ERR_PAY_STATE"] ;
			$ret['message'] = "此订单退款成功,订单关闭" ; 
			return $ret ;
		case 6 :
			$ret['status'] = $GLOBALS["ERR"]["ERR_PAY_STATE"] ;
			$ret['message'] = "请询价,请联系客服询问详细价格" ; 
			return $ret ;
		default :
			$ret['status'] = $GLOBALS["ERR"]["ERR_PAY_STATE"] ;
			$ret['message'] = $GLOBALS["MES"]["ERR_PAY_STATE"] ;
			return $ret ;
	}

	if (intval($one_trade['trade_class']) == 2){
	    // 众筹订单，检测众筹是否结束。
        $crowd_price_id = intval($one_trade['crowd_price_id']) ;
        $corwd = sql_fetch_one("select ci.* , unix_timestamp() as NowTM from crowd_price cp left join crowd_item ci on cp.crowd_id = ci.id where cp.id = '$crowd_price_id'") ;
        if (is_array($corwd) == false || array_key_exists('end_time' , $corwd) == false){
            $ret['status'] = $GLOBALS["ERR"]["ERR_PAY_STATE"] ;
            $ret['message'] = "此众筹已经失效,无法支付" ;
            return $ret ;
        }
        if ($corwd['NowTM'] - $corwd['end_time'] > 0){
            $ret['status'] = $GLOBALS["ERR"]["ERR_PAY_STATE"] ;
            $ret['message'] = "此众筹订单已经失效,无法支付" ;
            return $ret ;
        }
        if ($corwd['state'] >= 3){
            $ret['status'] = $GLOBALS["ERR"]["ERR_PAY_STATE"] ;
            $ret['message'] = "此众筹项目已经结束" ;
            return $ret ;
        }
        if ($one_trade['price_modify'] != $order_price){
            $ret['status'] = $GLOBALS["ERR"]["ERR_PAY_STATE"] ;
            $ret['message'] = "此众筹订单无法分次支付" ;
            return $ret ;
        }
    }

	// 价格不能小于0
	if (doubleval($one_trade['price']) < 0){
		$ret['status'] = $GLOBALS["ERR"]["ERR_PAY_ZERO"] ;
		$ret['message'] = $GLOBALS["MES"]["ERR_PAY_ZERO"] ;
		return $ret ;
	}
	// 价格不能为0
	if (doubleval($one_trade['price']) == 0  && doubleval($one_trade['price_modify']) == 0  ){
		$ret['status'] = $GLOBALS["ERR"]["ERR_PAY_ZERO"] ;
		$ret['message'] = $GLOBALS["MES"]["ERR_PAY_ZERO"] ;
		return $ret ;
	}
	// 订单价格更改后必须经过审核才允许用户付钱.
	if (doubleval($one_trade['price']) != doubleval($one_trade['price_modify'])){
		if (intval($one_trade['audit_state']) != 1){
			$ret['status'] = $GLOBALS["ERR"]["ERR_PAY_NOAUDIT"] ;
			$ret['message'] = $GLOBALS["MES"]["ERR_PAY_NOAUDIT"] ;
			return $ret ;
		}
	}

	if (check_all_trade_is_ok_pay($out_trade_no) == false){
        $ret['status'] = $GLOBALS["ERR"]["ERR_PAY_STATE"] ;
        $ret['message'] = "订单中有下架商品,无法支付" ;
        return $ret ;
    }


	$price_now = 0 ;		// 已经支付的金额
	$trade_count = 0 ;		// 已经支付的次数
	$alltrade = sql_fetch_rows("select * from `log_pay` where `trade_no` = '$out_trade_no' and `state` in (1 , 2)") ;
	if (is_array($alltrade)){
		foreach($alltrade as $at)
		{
			$price_now += doubleval($at['rmb']) ;
			$trade_count += 1 ;
		}
	}
	
	// 支付金额和汇总付款金额检测
	$money = doubleval($one_trade['price_modify']) ;		// 总共实际需要支付金额	
	// 本次支付请求支付的金额  $order_price	 
	if ((doubleval($order_price) + $price_now) > $money){
		$ret['status'] = $GLOBALS["ERR"]["ERR_PAY_ZERO"] ;
		$ret['message'] = "支付的金额过多." ;
		return $ret ;
	}
	// 支付次数的检测
	if ($pay_count <= 0)		$pay_count = 1 ;
	if ($pay_count - 1 != $trade_count){
		$ret['status'] = $GLOBALS["ERR"]["ERR_TRADE_INVITE"] ;
		$ret['message'] = "分次支付次数错误" ;
		return $ret ;
	}
	
	// 处理新订单,检测订单是否可支付
	$log_trade = sql_fetch_one("select * from `log_pay` where `trade_no` = '$out_trade_no' and `trade_no_count` = '$pay_count'") ;
	if (is_array($log_trade)){
		if (intval($log_trade['state']) != 1 && intval($log_trade['state']) != 2){
			// 删除作废的订单
			sql_query("delete from `log_pay` where `trade_no` = '$out_trade_no' and `trade_no_count` = '$pay_count'") ;
		}else{
			// 错误,此订单正在支付处理中.
			$ret['status'] = $GLOBALS["ERR"]["ERR_TRADE_INVITE"] ;
			$ret['message'] = "此订单正在支付处理中,请稍后,或联系客服" ;
			return $ret ;
		}
	}
	
	$ret['status'] = 0 ;
	$ret['trade'] = $one_trade ;
	return $ret ;
}
function pay_test_weixin($json)
{
	$ret = array() ;
	$ret['data'] = array() ;
	
	$order_price = 10 ;
	$body = "JAJAHOME付款 10 元" ;
	$update_wx_trade_no = "20170427_test_".date("s",time()) ;
	$result = getWeiXin_AppPay_unifiedorder($body , $update_wx_trade_no , $order_price) ;	
	
	$ret['data']['pay_info'] = $result ;
	
	return $ret ;
}

// 微信充值获取预充值数据参数(微信统一下单)
function pay_weixin_v2($json , $session)
{
	$ret = array() ;
	$ret['data'] = array() ;
	
	$uid = util_set_GETUID_for_SESSION($session) ;
	if ($uid <= 0)
	{
		$ret['status'] = $GLOBALS["ERR"]["ERR_USER_NOTFIND"] ;
		$ret['message'] = $GLOBALS["MES"]["ERR_USER_NOTFIND"] ;
		return $ret ;
	}
	
	$out_trade_no = get_jsonValue($json,"order_id") ;				// 我们自己的订单编号
	$order_price  = doubleval(get_jsonValue($json,"order_price")) ;	// 当前支付的金额
	$pay_count	  = intval(get_jsonValue($json,"pay_count")) ;		// 当前第几次支付（多次支付1开始累加）
	if ($pay_count <= 0)		$pay_count = 1 ;
	
	logsave("log_wx.txt" , "start pay_trade_state_check($out_trade_no , $uid , $order_price , $pay_count)") ;
	$ret = pay_trade_state_check($out_trade_no , $uid , $order_price , $pay_count) ;
	logsave("log_wx.txt" ," rnt = ".json_encode($ret)) ;
	
	if ($ret['status'] != 0){
		return $ret ;
	}
	$one_trade = $ret['trade'] ;

    $bkurl = "" ;
    if (intval($one_trade['trade_class']) == 2) {
        $bkurl = $GLOBALS['WX_NOTIFY_URL_CROWD'];
    }

    unset($ret['trade']) ;

	$body = "JAJAHOME付款 $order_price 元" ;
	$update_wx_trade_no = $out_trade_no."_".$pay_count."_".date("s",time()) ;
	
	logsave("log_wx.txt" , "getWeiXin_AppPay_unifiedorder($body , $update_wx_trade_no , $order_price)") ;
	$result = getWeiXin_AppPay_unifiedorder($body , $update_wx_trade_no , $order_price , $bkurl) ;
	logsave("log_wx.txt" ," rnt = ".json_encode($result)) ;
	    	
	    	
	if ($result['return_code'] == "SUCCESS" && $result['result_code'] == "SUCCESS")
	{
		// 统一下单成功		
		$prepay_id = $result['prepay_id'] ;	// 微信返回的支付交易会话ID		
		$memo_xml = $result['document_result'] ;		
		if (create_pay_beforehand_order($uid , $prepay_id , 1 , $out_trade_no , $pay_count , $memo_xml , $order_price) == false){
			$ret['status'] = $GLOBALS["ERR"]["ERR_DATABASE"] ;
			$ret['message'] = $GLOBALS["MES"]["ERR_DATABASE"] ;
			return $ret ;			
		}

		$param = array() ;
		$param["appid"]				= $GLOBALS['WX_APPID'];	// 公众账号ID
		$param["partnerid"]			= $GLOBALS['WX_MCHID'] ;	// 商户号
		$param["prepayid"]			= $prepay_id ;			// 微信返回的支付交易会话ID
		$param["noncestr"]			= md5("G8a2fe938d2j" . time());		// 随机字符串 不长于32位
		$param["timestamp"]			= time() ;					// 时间戳
		$param["package"]			= "Sign=WXPay" ;			// 暂填写固定值Sign=WXPay			
		$param["sign"]				= strtoupper(md5(getParamAuto($param,false) . "&key={$GLOBALS['WX_KEY']}")) ;
		

		$payinfo = array() ;
		$payinfo['error_code'] = 0 ;
		$payinfo['error_desc'] = "OK" ;
		$payinfo['partnerid'] 	= $param["partnerid"] ;		// 商户号
		$payinfo['prepayid'] 	= $param["prepayid"] ;		// 微信返回的支付交易会话ID
		$payinfo['noncestr'] 	= $param["noncestr"] ;		// 随机字符串 不长于32位
		$payinfo['timestamp'] 	= $param["timestamp"] ;		// 时间戳
		$payinfo['package'] 	= $param["package"] ;		// 暂填写固定值Sign=WXPay
		$payinfo['sign'] 		= $param["sign"] ;			// 签名
		$payinfo['appid'] 		= $param["appid"] ;		
		$payinfo['trade_no'] 	= $update_wx_trade_no ;		// 商户订单号
		
		
		$ret['data']['pay_info'] = $payinfo ;
	}
	else
	{
		$payinfo = array() ;
		$payinfo['error_code'] = $result['err_code'] ;
		$payinfo['error_desc'] = $result['err_code_des'] ;
		
		$ret['data']['pay_info'] = $payinfo ;
		
		$ret['status'] = 88 ;	// 下单失败
		$ret['message'] = "调用统一下单失败:" ;
		if ($result['return_code'] == "FAIL"){
			$ret['message'] .= $result['return_msg'] ;
		} 
		if ($result['return_code'] == "FAIL"){
			$ret['message'] .= "(" . $result['err_code'] . ")" . $result['err_code_des'];
		}
	}
	return $ret ;
}

//微信小程序的微信充值获取预充值数据参数(微信统一下单)
function pay_weixin_wx($json , $session)
{
    $ret = array() ;
    $ret['data'] = array() ;

    $uid = util_set_GETUID_for_SESSION($session) ;
    if ($uid <= 0)
    {
        $ret['status'] = $GLOBALS["ERR"]["ERR_USER_NOTFIND"] ;
        $ret['message'] = $GLOBALS["MES"]["ERR_USER_NOTFIND"] ;
        return $ret ;
    }

    $out_trade_no = get_jsonValue($json,"order_id") ;				// 我们自己的订单编号
    $order_price  = doubleval(get_jsonValue($json,"order_price")) ;	// 当前支付的金额
    $pay_count	  = intval(get_jsonValue($json,"pay_count")) ;		// 当前第几次支付（多次支付1开始累加）
	$open_id      = get_jsonValue($json,"openid") ;	                //微信用户的OPENID 
	
    if ($pay_count <= 0)		$pay_count = 1 ;

    logsave("log_wx.txt" , "start pay_trade_state_check($out_trade_no , $uid , $order_price , $pay_count)") ;
    $ret = pay_trade_state_check($out_trade_no , $uid , $order_price , $pay_count) ;
    logsave("log_wx.txt" ," rnt = ".json_encode($ret)) ;

    if ($ret['status'] != 0){
        return $ret ;
    }
    $one_trade = $ret['trade'] ;

    $bkurl = "" ;
    if (intval($one_trade['trade_class']) == 2) {
        $bkurl = $GLOBALS['WX_NOTIFY_URL_CROWD'];
    }

    unset($ret['trade']) ;

    $body = "JAJAHOME付款 $order_price 元" ;
    $update_wx_trade_no = $out_trade_no."_".$pay_count."_".date("s",time()) ;

    logsave("log_wx.txt" , "getWeiXin_AppPay_unifiedorder_v2($body , $update_wx_trade_no , $order_price , $open_id)") ;
    $result = getWeiXin_AppPay_unifiedorder_v2($body , $update_wx_trade_no , $order_price , $bkurl , $open_id) ;
    logsave("log_wx.txt" ," rnt = ".json_encode($result)) ;


    if ($result['return_code'] == "SUCCESS" && $result['result_code'] == "SUCCESS")
    {
        // 统一下单成功
        $prepay_id = $result['prepay_id'] ;	// 微信返回的支付交易会话ID
        $memo_xml = $result['document_result'] ;
        if (create_pay_beforehand_order($uid , $prepay_id , 1 , $out_trade_no , $pay_count , $memo_xml , $order_price) == false){
            $ret['status'] = $GLOBALS["ERR"]["ERR_DATABASE"] ;
            $ret['message'] = $GLOBALS["MES"]["ERR_DATABASE"] ;
            return $ret ;
        }

        $param = array() ;
        $param["appid"]				= 'wx6e228c4646b27eef';	// 公众账号ID
        $param["partnerid"]			= $GLOBALS['WX_MCHID'] ;	// 商户号
        $param["prepayid"]			= $prepay_id ;			// 微信返回的支付交易会话ID
        $param["noncestr"]			= md5("G8a2fe938d2j" . time());		// 随机字符串 不长于32位
        $param["timestamp"]			= time() ;					// 时间戳
        $param["package"]			= "Sign=WXPay" ;			// 暂填写固定值Sign=WXPay
		$param["openid"]	        = $open_id ;
        $param["sign"]				= strtoupper(md5(getParamAuto($param,false) . "&key={$GLOBALS['WX_KEY']}")) ;



        $payinfo = array() ;
        $payinfo['error_code'] = 0 ;
        $payinfo['error_desc'] = "OK" ;
        $payinfo['partnerid'] 	= $param["partnerid"] ;		// 商户号
        $payinfo['prepayid'] 	= $param["prepayid"] ;		// 微信返回的支付交易会话ID
        $payinfo['noncestr'] 	= $param["noncestr"] ;		// 随机字符串 不长于32位
        $payinfo['timestamp'] 	= $param["timestamp"] ;		// 时间戳
        $payinfo['package'] 	= $param["package"] ;		// 暂填写固定值Sign=WXPay
		$payinfo['openid'] 		= $param["openid"];		// 商户订单号
        $payinfo['sign'] 		= $param["sign"] ;			// 签名
        $payinfo['appid'] 		= $param["appid"] ;
        $payinfo['trade_no'] 	= $update_wx_trade_no ;		// 商户订单号


        $ret['data']['pay_info'] = $payinfo ;
    }
    else
    {
        $payinfo = array() ;
        $payinfo['error_code'] = $result['err_code'] ;
        $payinfo['error_desc'] = $result['err_code_des'] ;

        $ret['data']['pay_info'] = $payinfo ;

        $ret['status'] = 88 ;	// 下单失败
        $ret['message'] = "调用统一下单失败:" ;
        if ($result['return_code'] == "FAIL"){
            $ret['message'] .= $result['return_msg'] ;
        }
        if ($result['return_code'] == "FAIL"){
            $ret['message'] .= "(" . $result['err_code'] . ")" . $result['err_code_des'];
        }
    }
    return $ret ;
}
//TODO ---------------------------------------------------------------------

// 生成与支付订单
/**
 * uid    -- 支付用户,对应订单表的用户
 * prepay_id -- 订单唯一索引 - 微信为交易回话id , 支付宝为支付宝id (保证唯一)
 * type - 充值类型 1 - 微信 2 - 支付宝  5 - 转账
 * out_trade_no 我们订单表的订单号
 * pay_count   支付次数(多次支付的单子使用.)
 * memo_xml  -- 调用接口返回
 * order_price -- 预先支付的人民币(元)
 */
function create_pay_beforehand_order($uid , $prepay_id , $type , $out_trade_no , $pay_count , $memo_xml , $order_price)
{
	$base_state = 0 ;
	if ($type == 5){
		$base_state = 3 ;
	}
	
	sql_query("insert into `log_pay` (`prepay_id` , `transaction_id`, `trade_no`, `trade_no_count` , `uid`, `type`, `starttime`, `endtime`, `memo_xml`, `rmb`, `state`, `state_count`) VALUES ('$prepay_id' , '$prepay_id' , '$out_trade_no', '$pay_count' , '$uid', '$type', unix_timestamp(), '0', '$memo_xml', '$order_price', '$base_state', '0') ") ;
	$save_tr_id = sql_fetch_one_cell("select `prepay_id` from `log_pay` where `prepay_id` = '$prepay_id'") ;
	if ($prepay_id != $save_tr_id){		
		return false ;
	}
	return true ;
}



// 微信登陆验证用户接口
function getWeiXinUserinfo($access_token , $openid)
{
	$post_data = array() ;
	$post_data['access_token'] 	= $access_token;
	$post_data['openid'] 		= $openid;
	
	$url='https://api.weixin.qq.com/sns/userinfo?';		
	$res = post_net_data($url.getParamAuto($post_data));
	return $res ;
}
// 微信统一下单接口
function getWeiXin_AppPay_unifiedorder($body , $trade_no , $money , $bkurl)
{
	if ($GLOBALS['DEBUG_PAY'] == false){
		$wx_money = $money * 100 ;
	}else{
		$wx_money = 1 ;
	}
	
	if (is_null($bkurl) || $bkurl == "")  $bkurl = $GLOBALS['WX_NOTIFY_URL'] ;
	
	$param = array() ;
	$param["appid"]				= $GLOBALS['WX_APPID'] ;
	$param["mch_id"]			= $GLOBALS['WX_MCHID'] ;
	$param["nonce_str"]			= md5("8fgjj38d2" . time());			// 随机字符串 不长于32位
	$param["body"]				= $body ;								// 商品描述
	$param["out_trade_no"]		= $trade_no;							// 商户订单号
	$param["total_fee"]			= "$wx_money";							// 总金额,单位为分(测试都为1分钱) -- money * 100
	$param["spbill_create_ip"]	= $GLOBALS['WX_SPBILL_IP'];			// 终端IP , APP和网页支付提交用户端ip
	$param["notify_url"]		= $bkurl;								// 通知地址 , 接收微信支付异步通知回调地址，通知url必须为直接可访问的url，不能携带参数
	$param["trade_type"]		= "APP" ;								// 交易类型
	$param["time_start"]		= date("YmdHis",time());
	$param["time_expire"]		= date("YmdHis",time() + 600 * 1000);
	$param["sign"]				= strtoupper(md5(getParamAuto($param,false) . "&key={$GLOBALS['WX_KEY']}")) ;

	$send = getParamXml($param) ;
	$result = post_net_data2($GLOBALS['WX_SEND_unifiedorder'], $send) ;
	
	$dom = new DOMDocument();
	$dom->loadXML($result);
	$rntarr = getXMLArraySimp($dom->documentElement) ;
	$rntarr['document_result'] = $result ; 
	return $rntarr ;
}

// 微信统一下单接口
function getWeiXin_AppPay_unifiedorder_v2($body , $trade_no , $money , $bkurl , $open_id)
{
    if ($GLOBALS['DEBUG_PAY'] == false){
        $wx_money = $money * 100 ;
    }else{
        $wx_money = 1 ;
    }

    if (is_null($bkurl) || $bkurl == "")  $bkurl = $GLOBALS['WX_NOTIFY_URL'] ;

    $param = array() ;
    $param["appid"]				= 'wx6e228c4646b27eef' ;
    $param["mch_id"]			= $GLOBALS['WX_MCHID'] ;
    $param["nonce_str"]			= md5("8fgjj38d2" . time());			// 随机字符串 不长于32位
    $param["body"]				= $body ;								// 商品描述
    $param["out_trade_no"]		= $trade_no;							// 商户订单号
    $param["total_fee"]			= "$wx_money";							// 总金额,单位为分(测试都为1分钱) -- money * 100
    $param["spbill_create_ip"]	= $GLOBALS['WX_SPBILL_IP'];			// 终端IP , APP和网页支付提交用户端ip
    $param["notify_url"]		= $bkurl;								// 通知地址 , 接收微信支付异步通知回调地址，通知url必须为直接可访问的url，不能携带参数
    $param["trade_type"]		= "JSAPI" ;								// 交易类型
    $param["time_start"]		= date("YmdHis",time());
    $param["time_expire"]		= date("YmdHis",time() + 600 * 1000);
	$param["openid"]	        = $open_id ;
    $param["sign"]				= strtoupper(md5(getParamAuto($param,false) . "&key={$GLOBALS['WX_KEY']}")) ;

	
    $send = getParamXml($param) ;
    $result = post_net_data2($GLOBALS['WX_SEND_unifiedorder'], $send) ;

    $dom = new DOMDocument();
    $dom->loadXML($result);
    $rntarr = getXMLArraySimp($dom->documentElement) ;
    $rntarr['document_result'] = $result ;
    return $rntarr ;
}
// 微信查询订单接口
function getWeiXin_AppPay_orderquery($transaction_id , $out_trade_no)
{
	$param = array() ;
	$param["appid"]				= $GLOBALS['WX_APPID'] ;
	$param["mch_id"]			= $GLOBALS['WX_MCHID'] ;
	$param["nonce_str"]			= md5("8fee2j38d2" . time());			// 随机字符串 不长于32位
	if (strlen($transaction_id) > 5){
		$param["transaction_id"]		= $transaction_id ;
	}else{
		$param["out_trade_no"]			= $out_trade_no ;
	}
	$param["sign"]				= strtoupper(md5(getParamAuto($param,false) . "&key={$GLOBALS['WX_KEY']}")) ;
	$send = getParamXml($param) ;
	$result = post_net_data2($GLOBALS['WX_SEND_orderquery'], $send) ;
	
	$dom = new DOMDocument();
	$dom->loadXML($result);
	$rntarr = getXMLArraySimp($dom->documentElement) ;
	$rntarr['document_result'] = $result ; 
	return $rntarr ;
}

function getXMLArraySimp($node) 
{
	$array = false;
  	if ($node->hasAttributes()) {
    	foreach ($node->attributes as $attr) {
      		$array[$attr->nodeName] = $attr->nodeValue;
    	}
  	}
  
  	if ($node->hasChildNodes()) {
    	if ($node->childNodes->length == 1) {
      		$array[$node->firstChild->nodeName] = $node->firstChild->nodeValue ;
    	}else{
      		foreach ($node->childNodes as $childNode) {
      			if ($childNode->nodeType != XML_TEXT_NODE) {
        			$array[$childNode->nodeName] = $childNode->nodeValue ;
      			}
    		}
  		}
  	}else{
    	return $node->nodeValue;
  	}
  	return $array;
}

?>